// ==UserScript==
// @name         BatchWXVideoExtractor
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Extract WeChat Video Information with Apple-style UI
// @author       George Cai
// @match        https://channels.weixin.qq.com/platform/post/list
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    // 添加 Apple 风格的 CSS
    GM_addStyle(`
        .wx-extractor-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            padding: 8px 16px;
            background: rgba(0, 122, 255, 0.9);
            color: white;
            border: none;
            border-radius: 8px;
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", sans-serif;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
            z-index: 9999;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }

        .wx-extractor-btn:hover {
            background: rgba(0, 122, 255, 1);
            transform: scale(1.02);
        }

        .wx-extractor-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(255, 255, 255, 0.95);
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            z-index: 10000;
            width: 75%;
            max-width: 800px;
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
        }

        .wx-extractor-input {
            width: 100%;
            padding: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text";
            font-size: 14px;
            margin-bottom: 16px;
            background: rgba(255, 255, 255, 0.8);
        }

        .wx-extractor-textarea {
            width: 100%;
            height: 300px;
            margin: 16px 0;
            padding: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            font-family: "SF Mono", monospace;
            font-size: 14px;
            resize: none;
            background: rgba(255, 255, 255, 0.8);
        }

        .wx-extractor-button {
            background: rgba(0, 122, 255, 0.9);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            cursor: pointer;
            font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text";
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .wx-extractor-button:hover {
            background: rgba(0, 122, 255, 1);
        }

        .wx-extractor-close {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 30px;
            height: 30px;
            border: none;
            background: none;
            cursor: pointer;
            opacity: 0.6;
            transition: opacity 0.2s;
        }

        .wx-extractor-close:hover {
            opacity: 1;
        }

        .wx-extractor-close::before,
        .wx-extractor-close::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 2px;
            background-color: #000;
            top: 50%;
            left: 50%;
        }

        .wx-extractor-close::before {
            transform: translate(-50%, -50%) rotate(45deg);
        }

        .wx-extractor-close::after {
            transform: translate(-50%, -50%) rotate(-45deg);
        }
    `);

    // 创建提取按钮
    const extractButton = document.createElement('button');
    extractButton.className = 'wx-extractor-btn';
    extractButton.textContent = '提取视频信息';
    document.body.appendChild(extractButton);

    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'wx-extractor-modal';
    // 修改模态框 HTML，添加清除按钮
    modal.innerHTML = `
        <button class="wx-extractor-close"></button>
        <h2 style="margin: 0 0 16px 0; font-family: -apple-system, BlinkMacSystemFont;">提取视频信息</h2>
        <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 16px;">
            <input type="text" class="wx-extractor-input" placeholder="请输入 wxauthor_id" style="margin-bottom: 0;" />
            <button class="wx-extractor-button" id="clearAuthorId" style="background-color: #FF3B30; flex-shrink: 0;">
                清除ID
            </button>
        </div>
        <div style="display: flex; gap: 10px; margin-bottom: 16px;">
            <button class="wx-extractor-button" id="startExtract">开始提取</button>
            <button class="wx-extractor-button" id="clearResults" style="background-color: #FF3B30;">清除数据</button>
        </div>
        <textarea class="wx-extractor-textarea" readonly></textarea>
        <button class="wx-extractor-button" style="float: right;" id="copyButton">复制到剪贴板</button>
    `;

    document.body.appendChild(modal);

    // 获取必要的元素
    const closeButton = modal.querySelector('.wx-extractor-close');
    const input = modal.querySelector('.wx-extractor-input');
    const startButton = modal.querySelector('#startExtract');
    const textarea = modal.querySelector('.wx-extractor-textarea');
    const copyButton = modal.querySelector('#copyButton');

    // 提取按钮点击事件
    extractButton.addEventListener('click', () => {
        modal.style.display = 'block';
    });

    // 关闭按钮事件
    closeButton.addEventListener('click', () => {
        modal.style.display = 'none';
    });

    // 点击模态框外部关闭
    document.addEventListener('click', (e) => {
        if (!modal.contains(e.target) && e.target !== extractButton) {
            modal.style.display = 'none';
        }
    });

    // 获取新增的清除按钮
    const clearAuthorIdButton = modal.querySelector('#clearAuthorId');
    const clearResultsButton = modal.querySelector('#clearResults');

    // 添加清除 author_id 按钮事件
    clearAuthorIdButton.addEventListener('click', () => {
        if (confirm('确定要清除已保存的作者ID吗？')) {
            localStorage.removeItem('wx_extractor_author_id');
            input.value = '';
            alert('作者ID已清除！');
        }
    });

    // 添加清除结果按钮事件
    clearResultsButton.addEventListener('click', () => {
        if (confirm('确定要清除所有已提取的数据吗？')) {
            localStorage.removeItem('wx_extractor_results');
            textarea.value = '';
            alert('提取数据已清除！');
        }
    });

    // 修改提取完成后的处理
    startButton.addEventListener('click', async () => {
        const wxauthor_id = input.value.trim();
        if (!wxauthor_id) {
            alert('请输入 wxauthor_id');
            return;
        }

        // 保存 wxauthor_id 到 localStorage
        localStorage.setItem('wx_extractor_author_id', wxauthor_id);

        // 初始化或获取已存储的结果
        let results = JSON.parse(localStorage.getItem('wx_extractor_results') || '[]');
        
        async function extractCurrentPage() {
            const items = document.querySelectorAll('.post-list-body .post-feed-item');
            
            for (const item of items) {
                const copyButton = item.querySelector('.copy-feed-id');
                if (copyButton) {
                    modal.style.display = 'block';
                    
                    copyButton.click();
                    await new Promise(resolve => setTimeout(resolve, 100));
                    
                    const wxvideo_id = await navigator.clipboard.readText();
                    const title = item.querySelector('.post-title')?.textContent.trim() || '';
                    const cover = item.querySelector('.media > img')?.src || '';

                    results.push({
                        title,
                        cover,
                        wxauthor_id,
                        wxvideo_id
                    });
                }
            }

            // 保存当前结果到 localStorage
            localStorage.setItem('wx_extractor_results', JSON.stringify(results));
            
            // 更新显示
            textarea.value = JSON.stringify(results, null, 2);

            // 检查是否有下一页
            const nextPageButton = Array.from(document.querySelectorAll('span.weui-desktop-pagination__nav a')).find(a => a.textContent.includes('下一页'));
            
            if (nextPageButton) {
                nextPageButton.click();
                // 等待页面加载
                await new Promise(resolve => setTimeout(resolve, 1000));
                // 递归处理下一页
                await extractCurrentPage();
            }
        }

        // 开始提取
        // 修改 try-catch 块
        try {
            results = []; // 清空之前的结果
            localStorage.setItem('wx_extractor_results', '[]');
            await extractCurrentPage();
            
            // 确保弹窗显示并更新最终结果
            modal.style.display = 'block';
            textarea.value = JSON.stringify(results, null, 2);
            
            // 添加结果统计
            const totalCount = results.length;
            alert(`提取完成！共获取 ${totalCount} 条数据`);
        } catch (error) {
            console.error('提取过程出错：', error);
            modal.style.display = 'block'; // 错误时也显示弹窗
            alert('提取过程出错，请查看控制台获取详细信息');
        }
    });

    // 页面加载时恢复之前的数据
    window.addEventListener('load', () => {
        const savedAuthorId = localStorage.getItem('wx_extractor_author_id');
        const savedResults = localStorage.getItem('wx_extractor_results');
        
        if (savedAuthorId) {
            input.value = savedAuthorId;
        }
        
        if (savedResults) {
            textarea.value = JSON.stringify(JSON.parse(savedResults), null, 2);
        }
    });

    // 复制按钮事件
    copyButton.addEventListener('click', () => {
        textarea.select();
        document.execCommand('copy');
        copyButton.textContent = '已复制！';
        setTimeout(() => {
            copyButton.textContent = '复制到剪贴板';
        }, 2000);
    });
})();